﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using XWG.JWBST.JWBSTSPConst;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Data;
using XWG.Framework.AuthUtility;
using XWG.Framework.AuthSPConst;
using XWG.Framework.IAuthority;
using System.Collections;
using Newtonsoft.Json.Converters;

namespace JWBSTAPP.CommonClass
{
    public class WebHandlerBase : IHttpHandler
    {
        /// <summary>
        /// 返回类型类
        /// </summary>
        public class AjaxResultModel
        {
            public string result { get; set; }
            public int ErrorCode { get; set; }
            public int totalCount { get; set; }//总条数
            public int pageCount { get; set; }//总条数
            public object data { get; set; }//数据
            public string referer { get; set; }
        }
        string WebSessionMax = "0";//System.Configuration.ConfigurationManager.AppSettings["WebSessionMax"];
        string LimitIP = System.Configuration.ConfigurationManager.AppSettings["LimitIP"];
        /// <summary>
        /// 实现基类接口Request响应。（如果子类自定义ProcessRequest，子类需同时继承IHttpHandler来覆盖此方法）
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            AjaxResultModel mResultModel = new AjaxResultModel();
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            string callback = HttpContext.Current.Request["para"];
            string action = context.Request.Params["action"];
            var referer = context.Request.Headers["Referer"];
            if (action == null || referer == null)
            {
                mResultModel.result = "error";
                mResultModel.ErrorCode = -9989;
                HttpContext.Current.Response.Write(callback + "(" + JsonConvert.SerializeObject(mResultModel, dtConverter) + ")");
                HttpContext.Current.Response.End();
                return;
            }
            Uri u = new Uri(referer);
            //if (LimitIP != u.Host)
            //{
            //    mResultModel.result = "error";
            //    mResultModel.ErrorCode = -113;
            //    HttpContext.Current.Response.Write(callback + "(" + JsonConvert.SerializeObject(mResultModel, dtConverter) + ")");
            //    HttpContext.Current.Response.End();
            //    return;
            //}
            var ip = HttpContext.Current.Request.UserHostAddress;
            if (WebSessionMax != "0")
            {
                if (action.ToLower().Contains("add"))
                {
                    mResultModel.referer = ip;
                    var session = context.Session[ip];
                    if (session == null)
                    {
                        context.Session.Add(ip, DateTime.Now.ToString());
                        context.Session.Timeout = int.Parse(WebSessionMax);
                        mResultModel.result = "ok";
                    }
                    else
                    {
                        DateTime dt = new DateTime();
                        if (DateTime.TryParse(session.ToString(), out dt))
                        {
                            //判断时间差
                            TimeSpan ts = DateTime.Now - dt;
                            if (ts.TotalMinutes > int.Parse(WebSessionMax))
                            {
                                context.Session.Add(ip, DateTime.Now.ToString());
                                context.Session.Timeout = int.Parse(WebSessionMax);
                                mResultModel.result = "ok";
                            }
                            else
                            {
                                mResultModel.result = "error";
                            }
                        }
                        else
                        {
                            mResultModel.result = "error";
                        }
                    }
                }
            }
            if (mResultModel.result == "error")
            {
                mResultModel.ErrorCode = -110;
                mResultModel.data = null;
                mResultModel.totalCount = -1;
                mResultModel.pageCount = -1;
                HttpContext.Current.Response.Write(callback + "(" + JsonConvert.SerializeObject(mResultModel, dtConverter) + ")");
                HttpContext.Current.Response.End();
            }
            else
            {
                BindingFlags bf = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
                MethodInfo[] m = this.GetType().GetMethods(bf);
                if (String.IsNullOrEmpty(action))
                {
                    return;
                }
                MethodInfo mi = this.GetType().GetMethod("");
                if (this.GetType().GetMethod(ExMethodJWBST.Authority.Instance().GetMethodName(action), bf) != null)
                {
                    mi = this.GetType().GetMethod(ExMethodJWBST.Authority.Instance().GetMethodName(action), bf);

                }
                else if (this.GetType().GetMethod(action, bf) != null)
                {
                    mi = this.GetType().GetMethod(action, bf);
                }
                if (mi != null)
                {
                    PermissionMethodAttribute att = Attribute.GetCustomAttribute(mi, typeof(PermissionMethodAttribute)) as PermissionMethodAttribute;

                    if (att != null)
                    {
                        if (att.Check())
                            mi.Invoke(this, null);
                        else
                        {
                            mResultModel.result = "error";
                            mResultModel.ErrorCode = -9989;
                            HttpContext.Current.Response.Write(callback + "(" + JsonConvert.SerializeObject(mResultModel, dtConverter) + ")");
                            HttpContext.Current.Response.End();
                        }
                    }
                    else
                    {
                        mi.Invoke(this, null);
                    }
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}